﻿using Abp.Configuration;
using Abp.Localization;
using Abp.MultiTenancy;
using Microsoft.EntityFrameworkCore;
using Mt.Site.Core.Base.Localization;
using Mt.Site.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;

namespace Mt.Site.Migrations.Seed.Tenants
{
    public class DefaultTenantLanguagesCreator
    {
        public static List<ApplicationLanguage> InitialLanguages => GetInitialLanguages();

        private readonly MtSiteDbContext _context;
        private readonly int _tenantId;
        private static List<ApplicationLanguage> GetInitialLanguages()
        {
            return new List<ApplicationLanguage>
            {
                new MtApplicationLanguage(MultiTenancyConsts.DefaultTenantId, "zh-CN", "简体中文", "famfamfam-flags cn")
                //,new MtApplicationLanguage(MultiTenancyConsts.DefaultTenantId, "en", "English", "famfamfam-flags gb")
            };
        }

        public DefaultTenantLanguagesCreator(MtSiteDbContext context, int tenantId)
        {
            _context = context;
            _tenantId = tenantId;
        }

        public void Create()
        {
            CreateLanguages();
        }

        private void CreateLanguages()
        {
            foreach (var language in InitialLanguages)
            {
                AddLanguageIfNotExists(language);
            }

            AddSettingIfNotExists(LocalizationSettingNames.DefaultLanguage, "zh-CN", _tenantId);
        }

        private void AddLanguageIfNotExists(ApplicationLanguage language)
        {
            if (_context.Languages.IgnoreQueryFilters().Any(l => l.TenantId == _tenantId && l.Name == language.Name))
            {
                return;
            }
            language.TenantId = _tenantId;
            _context.Languages.Add(language);

            _context.SaveChanges();
        }

        private void AddSettingIfNotExists(string name, string value, int tenantId)
        {
            if (_context.Settings.IgnoreQueryFilters().Any(s => s.Name == name && s.TenantId == tenantId && s.UserId == null))
            {
                return;
            }

            _context.Settings.Add(new Setting(tenantId, null, name, value));
            _context.SaveChanges();
        }
    }
}
